package com.zshan.clinic.admin.service.patient;

import com.zshan.clinic.admin.constant.Constants;
import com.zshan.clinic.admin.entity.dto.MemberConsumeDTO;
import com.zshan.clinic.admin.entity.dto.MemberRechargeDTO;
import com.zshan.clinic.admin.entity.dto.MemberRefundDTO;
import com.zshan.clinic.admin.entity.vo.PatientMemberGearVo;
import com.zshan.clinic.admin.entity.vo.PatientMemberRechargeOrderVo;
import com.zshan.clinic.admin.entity.vo.PatientMemberTransVo;
import com.zshan.clinic.admin.entity.vo.PatientMemberVo;
import com.zshan.clinic.common.constant.CommonConstant;
import com.zshan.clinic.common.enums.MemberOrderStatusEnum;
import com.zshan.clinic.common.enums.MemberTransTypeEnum;
import com.zshan.clinic.common.enums.PayChannelEnum;
import com.zshan.clinic.common.enums.YesOrNoEnum;
import com.zshan.clinic.common.exception.BusinessFailException;
import com.zshan.clinic.common.util.page.PageInfo;
import com.zshan.clinic.common.util.page.PageUtils;
import com.zshan.clinic.common.util.string.StringUtil;
import com.zshan.clinic.common.util.uuid.IdBuilder;
import com.zshan.clinic.database.dao.*;
import com.zshan.clinic.database.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 会员档位
 */
@Service
@Slf4j
public class ClinicMemberService {

    /**
     * 会员卡
     */
    @Autowired
    private ClinicPatientMemberMapper patientMemberMapper;

    /**
     * 充值档位
     */
    @Autowired
    private PatientMemberGearMapper patientMemberGearMapper;

    /**
     * 充值订单
     */
    @Autowired
    private PatientMemberRechargeOrderMapper patientMemberRechargeOrderMapper;

    /**
     * 退款订单
     */
    @Autowired
    private PatientMemberRefundOrderMapper patientMemberRefundOrderMapper;

    /**
     * 会员卡交易流水
     */
    @Autowired
    private PatientMemberTransMapper patientMemberTransMapper;


    @Autowired
    private ClinicPatientService patientService;

    /**
     * 查询患者会员卡余额
     * @param patientId
     * @return
     */
    public PatientMemberVo getMemberBalance(Long clinicId,Long patientId){
        ClinicPatientMember patientMember = patientMemberMapper.selectByPrimaryKey(patientId);
        if(patientMember == null){
            return PatientMemberVo.buildDefault(patientId);
        }
        PatientMemberVo patientMemberVo = new PatientMemberVo();
        BeanUtils.copyProperties(patientMember,patientMemberVo);
        return patientMemberVo;
    }


    /**
     * 查询订单交易流水
     * @param clinicId
     * @param patientId
     * @param transNo
     * @param transType
     * @param pageNo
     * @param pageSize
     * @return
     */
    public PageInfo<PatientMemberTransVo> getTransList(Long clinicId, Long patientId, String transNo, String transType, Integer pageNo, Integer pageSize){
        PageInfo<PatientMemberTrans> pageInfo = getTransListByCondition(clinicId,patientId,transNo,transType,pageNo,pageSize);
        if(pageInfo.getTotalCount() <= CommonConstant.DEFAULT_0){
            return PageInfo.build();
        }
        List<PatientMemberTrans> logList = pageInfo.getList();
        // 将实体列表转换为DTO列表
        return new PageInfo<>(pageInfo.getTotalCount(),logList.stream().map(order -> {
            PatientMemberTransVo orderVo = new PatientMemberTransVo();
            BeanUtils.copyProperties(order, orderVo);
            return orderVo;
        }).collect(Collectors.toList()));
    }
    /**
     * 查询充值订单
     * @param clinicId
     * @param patientId
     * @param orderNo
     * @param orderStatus
     * @param pageNo
     * @param pageSize
     * @return
     */
    public PageInfo<PatientMemberRechargeOrderVo> getRechargeList(Long clinicId, Long patientId, String orderNo, String orderStatus, Integer pageNo, Integer pageSize){
        PageInfo<PatientMemberRechargeOrder> pageInfo = getRechargeOrderListByCondition(clinicId,patientId,orderNo,orderStatus,pageNo,pageSize);
        if(pageInfo.getTotalCount() <= CommonConstant.DEFAULT_0){
            return PageInfo.build();
        }
        List<PatientMemberRechargeOrder> logList = pageInfo.getList();
        // 将实体列表转换为DTO列表
        return new PageInfo<>(pageInfo.getTotalCount(),logList.stream().map(order -> {
            PatientMemberRechargeOrderVo orderVo = new PatientMemberRechargeOrderVo();
            BeanUtils.copyProperties(order, orderVo);
            if(StringUtil.isBlank(orderVo.getUpdateBy())){
                orderVo.setUpdateBy(order.getCreateBy());
            }
            if(orderVo.getUpdateTime() == null){
                orderVo.setUpdateTime(order.getCreateTime());
            }
            return orderVo;
        }).collect(Collectors.toList()));
    }


    /**
     * 会员充值
     * @param memberRechargeDTO
     */
    @Transactional(rollbackFor = Exception.class)
    public void recharge(MemberRechargeDTO memberRechargeDTO){
        ClinicPatient patientInfo = patientService.getPatientById(memberRechargeDTO.getPatientId());
        if(patientInfo == null){
            throw new BusinessFailException("患者不存在");
        }
        PatientMemberGear memberGear = getGearById(memberRechargeDTO.getGearId());
        if(memberGear == null){
            throw new BusinessFailException("档位不存在");
        }
        if(StringUtil.isBlank(memberRechargeDTO.getPayChannel())){
            throw new BusinessFailException("请选择支付渠道");
        }
        if(!PayChannelEnum.isValue(memberRechargeDTO.getPayChannel())){
            throw new BusinessFailException("支付渠道错误");
        }
        //添加充值订单
        String orderNo = IdBuilder.getUniqueId("CZ");
        addRechargeOrder(orderNo,patientInfo,memberRechargeDTO,memberGear);
        //修改账户余额
        addBalance(orderNo,memberRechargeDTO,patientInfo,memberGear);
    }

    /**
     * 会员卡充值
     * @param memberRechargeDTO
     * @param patientInfo
     * @param memberGear
     */
    @Transactional(rollbackFor = Exception.class)
    public void addBalance(String orderNo,MemberRechargeDTO memberRechargeDTO,ClinicPatient patientInfo,PatientMemberGear memberGear) {
        ClinicPatientMember patientMember = getMemberById(patientInfo.getPatientId());
        if(patientMember == null){
            patientMember = new ClinicPatientMember();
            patientMember.setPatientId(patientInfo.getPatientId());
            patientMember.setPatientName(patientInfo.getPatientName());
            patientMember.setBalance(memberGear.getRechargeAmount());
            patientMember.setLastRechargeTime(new Date());
            patientMember.setClinicId(memberRechargeDTO.getClinicId());
            patientMember.setCreateUserId(memberRechargeDTO.getCreateUserId());
            patientMember.setCreateBy(memberRechargeDTO.getCreateBy());
            addMember(patientMember);
        }else {
            patientMember.setPatientName(patientInfo.getPatientName());
            patientMember.setBalance(patientMember.getBalance() + memberGear.getRechargeAmount());
            patientMember.setLastRechargeTime(new Date());
            patientMember.setClinicId(memberRechargeDTO.getClinicId());
            patientMember.setUpdateUserId(memberRechargeDTO.getCreateUserId());
            patientMember.setUpdateBy(memberRechargeDTO.getCreateBy());
            updateMember(patientMember);
        }
        //增加账户流水
        PatientMemberTrans patientMemberTrans = new PatientMemberTrans();
        patientMemberTrans.setPatientId(patientMember.getPatientId());
        patientMemberTrans.setTransNo(IdBuilder.getUniqueId("T"));
        patientMemberTrans.setTransType(MemberTransTypeEnum.RECHARGE.getValue());
        patientMemberTrans.setAmount(memberGear.getRechargeAmount());
        patientMemberTrans.setTransTime(new Date());
        patientMemberTrans.setOrderNo(orderNo);
        patientMemberTrans.setClinicId(memberRechargeDTO.getClinicId());
        patientMemberTrans.setCreateUserId(memberRechargeDTO.getCreateUserId());
        patientMemberTrans.setCreateBy(memberRechargeDTO.getCreateBy());
        addTrans(patientMemberTrans);
    }


    public void validateRechargeDTO(MemberRechargeDTO memberRechargeDTO) {
        ClinicPatient patientInfo = patientService.getPatientById(memberRechargeDTO.getPatientId());
        if(patientInfo == null){
            throw new BusinessFailException("患者不存在");
        }
        PatientMemberGear memberGear = getGearById(memberRechargeDTO.getGearId());
        if(memberGear == null){
            throw new BusinessFailException("档位不存在");
        }
        if(StringUtil.isBlank(memberRechargeDTO.getPayChannel())){
            throw new BusinessFailException("请选择支付渠道");
        }
        if(!PayChannelEnum.isValue(memberRechargeDTO.getPayChannel())){
            throw new BusinessFailException("支付渠道错误");
        }
    }

    /**
     * 退款订单
     * @param memberRefundDTO
     */
    @Transactional(rollbackFor = Exception.class)
    public void refund(MemberRefundDTO memberRefundDTO){
        PatientMemberRechargeOrder dbRechargeOrder = getRechargeOrderById(memberRefundDTO.getOrderId());
        if(dbRechargeOrder == null){
            throw new BusinessFailException("充值订单不存在");
        }
        if(!MemberOrderStatusEnum.SUCCESS.getValue().equals(dbRechargeOrder.getOrderStatus())){
            throw new BusinessFailException("订单状态不允许");
        }
        ClinicPatientMember patientMember = getMemberById(dbRechargeOrder.getPatientId());
        if(patientMember == null){
            throw new BusinessFailException("会员卡不存在");
        }
        if(dbRechargeOrder.getRechargeAmount() > patientMember.getBalance()){
            throw new BusinessFailException("当前余额不足，无法完成退款");
        }
        //更新订单状态
        dbRechargeOrder.setOrderStatus(MemberOrderStatusEnum.REFUND.getValue());
        dbRechargeOrder.setUpdateUserId(memberRefundDTO.getCreateUserId());
        dbRechargeOrder.setUpdateBy(memberRefundDTO.getCreateBy());
        dbRechargeOrder.setUpdateTime(new Date());
        patientMemberRechargeOrderMapper.updateByPrimaryKeySelective(dbRechargeOrder);
        //保存退款订单
        String orderNo = IdBuilder.getUniqueId("T");
        PatientMemberRefundOrder refundOrder = new PatientMemberRefundOrder();
        refundOrder.setPatientId(dbRechargeOrder.getPatientId());
        refundOrder.setPatientName(dbRechargeOrder.getPatientName());
        refundOrder.setOrderNo(orderNo);
        refundOrder.setOrderTime(new Date());
        refundOrder.setRefundAmount(dbRechargeOrder.getRechargeAmount());
        refundOrder.setRechargeOrderNo(dbRechargeOrder.getOrderNo());
        refundOrder.setClinicId(memberRefundDTO.getClinicId());
        refundOrder.setCreateUserId(memberRefundDTO.getCreateUserId());
        refundOrder.setCreateBy(memberRefundDTO.getCreateBy());
        addRefundOrder(refundOrder);
        //扣款
        deductBalance(
                memberRefundDTO.getClinicId(),
                patientMember.getPatientId(),
                MemberTransTypeEnum.REFUND.getValue(),
                orderNo,
                refundOrder.getRefundAmount(),
                memberRefundDTO.getCreateUserId(),
                memberRefundDTO.getCreateBy()
        );
    }


    /**
     * 扣款
     * @param clinicId 诊所
     * @param patientId 患者ID
     * @param transType 交易类型
     * @param orderNo 业务订单号
     * @param amount 交易金额
     * @param createUserId
     * @param creatBy
     */
    @Transactional(rollbackFor = Exception.class)
    public void deductBalance(Long clinicId,Long patientId,String transType,String orderNo,Integer amount,Long createUserId,String creatBy){
        ClinicPatientMember patientMember = getMemberById(patientId);
        if(patientMember == null){
            throw new BusinessFailException("会员卡不存在");
        }
        if(amount > patientMember.getBalance()){
            throw new BusinessFailException("余额不足");
        }
        //扣款
        patientMember.setBalance(patientMember.getBalance() - amount);
        patientMember.setUpdateUserId(createUserId);
        patientMember.setUpdateBy(creatBy);
        updateMember(patientMember);
        //增加账户流水
        PatientMemberTrans patientMemberTrans = new PatientMemberTrans();
        patientMemberTrans.setPatientId(patientMember.getPatientId());
        patientMemberTrans.setTransNo(IdBuilder.getUniqueId("T"));
        patientMemberTrans.setTransType(transType);
        patientMemberTrans.setAmount(amount);
        patientMemberTrans.setTransTime(new Date());
        patientMemberTrans.setOrderNo(orderNo);
        patientMemberTrans.setClinicId(clinicId);
        patientMemberTrans.setCreateUserId(createUserId);
        patientMemberTrans.setCreateBy(creatBy);
        addTrans(patientMemberTrans);
    }

    /**
     * 消费
     * @param memberConsumeDTO
     */
    @Transactional(rollbackFor = Exception.class)
    public void consume(MemberConsumeDTO memberConsumeDTO){
        ClinicPatientMember patientMember = getMemberById(memberConsumeDTO.getPatientId());
        if(patientMember == null){
            throw new BusinessFailException("会员卡不存在");
        }
        if(memberConsumeDTO.getAmount() > patientMember.getBalance()){
            throw new BusinessFailException("余额不足");
        }
        //扣款
        deductBalance(
                memberConsumeDTO.getClinicId(),
                patientMember.getPatientId(),
                MemberTransTypeEnum.CONSUMPTION.getValue(),
                memberConsumeDTO.getOrderNo(),
                memberConsumeDTO.getAmount(),
                memberConsumeDTO.getCreateUserId(),
                memberConsumeDTO.getCreateBy()
        );
    }




    /**
     * 分页查询退款订单
     * @param clinicId 诊所ID
     * @param orderNo 订单号（模糊搜索）
     * @param pageNo 页码
     * @param pageSize 每页数量
     * @return 分页结果
     */
    public PageInfo<PatientMemberRefundOrder> getRefundOrderListByCondition(Long clinicId, String orderNo, Integer pageNo, Integer pageSize) {
        PatientMemberRefundOrderExample example = new PatientMemberRefundOrderExample();
        PatientMemberRefundOrderExample.Criteria criteria = example.createCriteria();
        if (StringUtil.isNotBlank(orderNo)) {
            criteria.andOrderNoLike("%" + orderNo + "%");
        }
        if (!StringUtil.isBlank(clinicId)) {
            criteria.andClinicIdEqualTo(clinicId);
        }
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        Long totalCount = patientMemberRefundOrderMapper.countByExample(example);
        if (totalCount == null || totalCount == 0) {
            return PageInfo.build();
        }
        example.setOffset(PageUtils.getOffset(pageNo, pageSize));
        example.setLimit(pageSize);
        example.setOrderByClause("create_time desc");
        List<PatientMemberRefundOrder> orderList = patientMemberRefundOrderMapper.selectByExample(example);
        return new PageInfo<>(totalCount, orderList);
    }

    /**
     * 添加退款订单
     * @param refundOrder 实体
     */
    @Transactional(rollbackFor = Exception.class)
    public void addRefundOrder(PatientMemberRefundOrder refundOrder) {
        validateRefundOrder(refundOrder);
        refundOrder.setIsDelete(YesOrNoEnum.NO.getValue());
        refundOrder.setIsEnabled(YesOrNoEnum.YES.getValue());
        refundOrder.setCreateTime(new Date());
        patientMemberRefundOrderMapper.insertSelective(refundOrder);
    }

    /**
     * 校验退款订单
     * @param order 实体
     */
    public void validateRefundOrder(PatientMemberRefundOrder order) {
        if (StringUtil.isBlank(order.getOrderNo())) {
            throw new BusinessFailException("退款订单号不能为空");
        }
        if (order.getRefundAmount() == null || order.getRefundAmount() <= CommonConstant.DEFAULT_0) {
            throw new BusinessFailException("退款金额必须大于" + CommonConstant.DEFAULT_0);
        }
    }

    /**
     * 根据主键查询退款订单
     * @param orderId 主键ID
     * @return 实体
     */
    public PatientMemberRefundOrder getRefundOrderById(Long orderId) {
        if (orderId == null) {
            return null;
        }
        PatientMemberRefundOrder order = patientMemberRefundOrderMapper.selectByPrimaryKey(orderId);
        if (order == null || YesOrNoEnum.YES.getValue().equals(order.getIsDelete())) {
            return null;
        }
        return order;
    }

    /**
     * 修改退款订单
     * @param refundOrder 实体
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateRefundOrder(PatientMemberRefundOrder refundOrder) {
        validateRefundOrder(refundOrder);
        PatientMemberRefundOrder dbOrder = getRefundOrderById(refundOrder.getOrderId());
        if (dbOrder == null) {
            throw new BusinessFailException("退款订单不存在");
        }
        refundOrder.setUpdateTime(new Date());
        patientMemberRefundOrderMapper.updateByPrimaryKeySelective(refundOrder);
    }

    /**
     * 删除退款订单（逻辑删除）
     * @param refundOrder 实体
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteRefundOrder(PatientMemberRefundOrder refundOrder) {
        PatientMemberRefundOrder dbOrder = getRefundOrderById(refundOrder.getOrderId());
        if (dbOrder == null) {
            throw new BusinessFailException("退款订单不存在");
        }
        dbOrder.setIsDelete(YesOrNoEnum.YES.getValue());
        dbOrder.setUpdateUserId(refundOrder.getUpdateUserId());
        dbOrder.setUpdateBy(refundOrder.getUpdateBy());
        dbOrder.setUpdateTime(new Date());
        patientMemberRefundOrderMapper.updateByPrimaryKeySelective(dbOrder);
    }

    /**
     * 启用退款订单
     * @param refundOrder 实体
     */
    @Transactional(rollbackFor = Exception.class)
    public void enableRefundOrder(PatientMemberRefundOrder refundOrder) {
        PatientMemberRefundOrder dbOrder = getRefundOrderById(refundOrder.getOrderId());
        if (dbOrder == null) {
            throw new BusinessFailException("退款订单不存在");
        }
        if (YesOrNoEnum.YES.getValue().equals(dbOrder.getIsEnabled())) {
            return;
        }
        dbOrder.setIsEnabled(YesOrNoEnum.YES.getValue());
        dbOrder.setUpdateUserId(refundOrder.getUpdateUserId());
        dbOrder.setUpdateBy(refundOrder.getUpdateBy());
        dbOrder.setUpdateTime(new Date());
        patientMemberRefundOrderMapper.updateByPrimaryKeySelective(dbOrder);
    }

    /**
     * 停用退款订单
     * @param refundOrder 实体
     */
    @Transactional(rollbackFor = Exception.class)
    public void disableRefundOrder(PatientMemberRefundOrder refundOrder) {
        PatientMemberRefundOrder dbOrder = getRefundOrderById(refundOrder.getOrderId());
        if (dbOrder == null) {
            throw new BusinessFailException("退款订单不存在");
        }
        if (YesOrNoEnum.NO.getValue().equals(dbOrder.getIsEnabled())) {
            return;
        }
        dbOrder.setIsEnabled(YesOrNoEnum.NO.getValue());
        dbOrder.setUpdateUserId(refundOrder.getUpdateUserId());
        dbOrder.setUpdateBy(refundOrder.getUpdateBy());
        dbOrder.setUpdateTime(new Date());
        patientMemberRefundOrderMapper.updateByPrimaryKeySelective(dbOrder);
    }



    /**
     * 分页查询充值订单
     * @param clinicId 诊所ID
     * @param orderNo 订单号（模糊搜索）
     * @param pageNo 页码
     * @param pageSize 每页数量
     * @return 分页结果
     */
    public PageInfo<PatientMemberRechargeOrder> getRechargeOrderListByCondition(Long clinicId, Long patientId,String orderNo, String orderStatus,Integer pageNo, Integer pageSize) {
        PatientMemberRechargeOrderExample example = new PatientMemberRechargeOrderExample();
        PatientMemberRechargeOrderExample.Criteria criteria = example.createCriteria();
        if(!StringUtil.isBlank(patientId)){
            criteria.andPatientIdEqualTo(patientId);
        }
        if (StringUtil.isNotBlank(orderNo)) {
            criteria.andOrderNoEqualTo(orderNo);
        }
        if(StringUtil.isNotBlank(orderStatus)){
            criteria.andOrderStatusEqualTo(orderStatus);
        }
        criteria.andClinicIdEqualTo(clinicId);
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        Long totalCount = patientMemberRechargeOrderMapper.countByExample(example);
        if (totalCount == null || totalCount == 0) {
            return PageInfo.build();
        }
        example.setOffset(PageUtils.getOffset(pageNo, pageSize));
        example.setLimit(pageSize);
        example.setOrderByClause("create_time desc");
        List<PatientMemberRechargeOrder> orderList = patientMemberRechargeOrderMapper.selectByExample(example);
        return new PageInfo<>(totalCount, orderList);
    }


    /**
     * 添加充值订单
     * @param orderNo
     * @param patientInfo
     * @param memberRechargeDTO
     * @param memberGear
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public PatientMemberRechargeOrder addRechargeOrder(String orderNo,ClinicPatient patientInfo,MemberRechargeDTO memberRechargeDTO,PatientMemberGear memberGear) {
        PatientMemberRechargeOrder rechargeOrder = new PatientMemberRechargeOrder();
        rechargeOrder.setPatientId(memberRechargeDTO.getPatientId());
        rechargeOrder.setPatientName(patientInfo.getPatientName());
        rechargeOrder.setOrderNo(orderNo);
        rechargeOrder.setOrderTime(new Date());
        rechargeOrder.setGearId(memberRechargeDTO.getGearId());
        rechargeOrder.setGearName(memberGear.getGearName());
        rechargeOrder.setPayChannel(memberRechargeDTO.getPayChannel());
        rechargeOrder.setOrderStatus(MemberOrderStatusEnum.SUCCESS.getValue());
        rechargeOrder.setRechargeAmount(memberGear.getRechargeAmount());
        rechargeOrder.setPayAmount(memberGear.getPresentPrice());
        rechargeOrder.setClinicId(memberRechargeDTO.getClinicId());
        rechargeOrder.setCreateUserId(memberRechargeDTO.getCreateUserId());
        rechargeOrder.setCreateBy(memberRechargeDTO.getCreateBy());
        rechargeOrder.setIsDelete(YesOrNoEnum.NO.getValue());
        rechargeOrder.setIsEnabled(YesOrNoEnum.YES.getValue());
        rechargeOrder.setCreateTime(new Date());
        patientMemberRechargeOrderMapper.insertSelective(rechargeOrder);
        return rechargeOrder;
    }

    /**
     * 校验充值订单
     * @param order 实体
     */
    public void validateRechargeOrder(PatientMemberRechargeOrder order) {
        if (StringUtil.isBlank(order.getOrderNo())) {
            throw new BusinessFailException("订单号不能为空");
        }
        if (order.getRechargeAmount() == null || order.getRechargeAmount() <= CommonConstant.DEFAULT_0) {
            throw new BusinessFailException("充值金额必须大于" + CommonConstant.DEFAULT_0);
        }
    }

    /**
     * 根据主键查询充值订单
     * @param orderId 主键ID
     * @return 实体
     */
    public PatientMemberRechargeOrder getRechargeOrderById(Long orderId) {
        if (orderId == null) {
            return null;
        }
        PatientMemberRechargeOrder order = patientMemberRechargeOrderMapper.selectByPrimaryKey(orderId);
        if (order == null || YesOrNoEnum.YES.getValue().equals(order.getIsDelete())) {
            return null;
        }
        return order;
    }

    /**
     * 修改充值订单
     * @param order 实体
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateRechargeOrder(PatientMemberRechargeOrder order) {
        validateRechargeOrder(order);
        PatientMemberRechargeOrder dbOrder = getRechargeOrderById(order.getOrderId());
        if (dbOrder == null) {
            throw new BusinessFailException("充值订单不存在");
        }
        order.setUpdateTime(new Date());
        patientMemberRechargeOrderMapper.updateByPrimaryKeySelective(order);
    }




    /**
     * 删除充值订单（逻辑删除）
     * @param order 实体
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteRechargeOrder(PatientMemberRechargeOrder order) {
        PatientMemberRechargeOrder dbOrder = getRechargeOrderById(order.getOrderId());
        if (dbOrder == null) {
            throw new BusinessFailException("充值订单不存在");
        }
        dbOrder.setIsDelete(YesOrNoEnum.YES.getValue());
        dbOrder.setUpdateUserId(order.getUpdateUserId());
        dbOrder.setUpdateBy(order.getUpdateBy());
        dbOrder.setUpdateTime(new Date());
        patientMemberRechargeOrderMapper.updateByPrimaryKeySelective(dbOrder);
    }

    /**
     * 启用充值订单
     * @param order 实体
     */
    @Transactional(rollbackFor = Exception.class)
    public void enableRechargeOrder(PatientMemberRechargeOrder order) {
        PatientMemberRechargeOrder dbOrder = getRechargeOrderById(order.getOrderId());
        if (dbOrder == null) {
            throw new BusinessFailException("充值订单不存在");
        }
        if (YesOrNoEnum.YES.getValue().equals(dbOrder.getIsEnabled())) {
            return;
        }
        dbOrder.setIsEnabled(YesOrNoEnum.YES.getValue());
        dbOrder.setUpdateUserId(order.getUpdateUserId());
        dbOrder.setUpdateBy(order.getUpdateBy());
        dbOrder.setUpdateTime(new Date());
        patientMemberRechargeOrderMapper.updateByPrimaryKeySelective(dbOrder);
    }

    /**
     * 停用充值订单
     * @param order 实体
     */
    @Transactional(rollbackFor = Exception.class)
    public void disableRechargeOrder(PatientMemberRechargeOrder order) {
        PatientMemberRechargeOrder dbOrder = getRechargeOrderById(order.getOrderId());
        if (dbOrder == null) {
            throw new BusinessFailException("充值订单不存在");
        }
        if (YesOrNoEnum.NO.getValue().equals(dbOrder.getIsEnabled())) {
            return;
        }
        dbOrder.setIsEnabled(YesOrNoEnum.NO.getValue());
        dbOrder.setUpdateUserId(order.getUpdateUserId());
        dbOrder.setUpdateBy(order.getUpdateBy());
        dbOrder.setUpdateTime(new Date());
        patientMemberRechargeOrderMapper.updateByPrimaryKeySelective(dbOrder);
    }




    /**
     * 分页查询会员卡交易流水
     */
    public PageInfo<PatientMemberTrans> getTransListByCondition(Long clinicId, Long patientId, String transNo, String transType,  Integer pageNo, Integer pageSize) {
        PatientMemberTransExample example = new PatientMemberTransExample();
        PatientMemberTransExample.Criteria criteria = example.createCriteria();
        if(!StringUtil.isBlank(patientId)){
            criteria.andPatientIdEqualTo(patientId);
        }
        if (StringUtil.isNotBlank(transNo)) {
            criteria.andTransNoEqualTo(transNo);
        }
        if (StringUtil.isNotBlank(transType)) {
            criteria.andTransTypeEqualTo(transType);
        }
        criteria.andClinicIdEqualTo(clinicId);
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        Long totalCount = patientMemberTransMapper.countByExample(example);
        if (totalCount == null || totalCount == 0) {
            return PageInfo.build();
        }
        example.setOffset(PageUtils.getOffset(pageNo, pageSize));
        example.setLimit(pageSize);
        example.setOrderByClause("create_time desc");
        List<PatientMemberTrans> transList = patientMemberTransMapper.selectByExample(example);
        return new PageInfo<>(totalCount, transList);
    }

    /**
     * 添加会员卡交易流水
     */
    @Transactional(rollbackFor = Exception.class)
    public void addTrans(PatientMemberTrans patientMemberTrans) {
        validateTrans(patientMemberTrans);
        patientMemberTrans.setIsDelete(YesOrNoEnum.NO.getValue());
        patientMemberTrans.setIsEnabled(YesOrNoEnum.YES.getValue());
        patientMemberTrans.setCreateTime(new Date());
        patientMemberTransMapper.insertSelective(patientMemberTrans);
    }

    /**
     * 校验会员卡交易流水
     */
    public void validateTrans(PatientMemberTrans trans) {
        if (StringUtil.isBlank(trans.getTransNo())) {
            throw new BusinessFailException("交易流水号不能为空");
        }
        if (trans.getAmount() == null || trans.getAmount() <= CommonConstant.DEFAULT_0) {
            throw new BusinessFailException("交易金额必须大于" + CommonConstant.DEFAULT_0);
        }
        if (trans.getTransType() == null) {
            throw new BusinessFailException("交易类型不能为空");
        }
        if(!MemberTransTypeEnum.isValue(trans.getTransType())){
            throw new BusinessFailException("交易类型错误");
        }
    }

    /**
     * 根据主键查询交易流水
     */
    public PatientMemberTrans getTransById(Long transId) {
        if (transId == null) {
            return null;
        }
        PatientMemberTrans trans = patientMemberTransMapper.selectByPrimaryKey(transId);
        if (trans == null || YesOrNoEnum.YES.getValue().equals(trans.getIsDelete())) {
            return null;
        }
        return trans;
    }

    /**
     * 修改会员卡交易流水
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateTrans(PatientMemberTrans patientMemberTrans) {
        validateTrans(patientMemberTrans);
        PatientMemberTrans dbTrans = getTransById(patientMemberTrans.getTransId());
        if (dbTrans == null) {
            throw new BusinessFailException("交易流水不存在");
        }
        patientMemberTrans.setUpdateTime(new Date());
        patientMemberTransMapper.updateByPrimaryKeySelective(patientMemberTrans);
    }

    /**
     * 删除会员卡交易流水（逻辑删除）
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteTrans(PatientMemberTrans patientMemberTrans) {
        PatientMemberTrans dbTrans = getTransById(patientMemberTrans.getTransId());
        if (dbTrans == null) {
            throw new BusinessFailException("交易流水不存在");
        }
        dbTrans.setIsDelete(YesOrNoEnum.YES.getValue());
        dbTrans.setUpdateUserId(patientMemberTrans.getUpdateUserId());
        dbTrans.setUpdateBy(patientMemberTrans.getUpdateBy());
        dbTrans.setUpdateTime(new Date());
        patientMemberTransMapper.updateByPrimaryKeySelective(dbTrans);
    }

    /**
     * 启用交易流水
     */
    @Transactional(rollbackFor = Exception.class)
    public void enableTrans(PatientMemberTrans patientMemberTrans) {
        PatientMemberTrans dbTrans = getTransById(patientMemberTrans.getTransId());
        if (dbTrans == null) {
            throw new BusinessFailException("交易流水不存在");
        }
        if (YesOrNoEnum.YES.getValue().equals(dbTrans.getIsEnabled())) {
            return;
        }
        dbTrans.setIsEnabled(YesOrNoEnum.YES.getValue());
        dbTrans.setUpdateUserId(patientMemberTrans.getUpdateUserId());
        dbTrans.setUpdateBy(patientMemberTrans.getUpdateBy());
        dbTrans.setUpdateTime(new Date());
        patientMemberTransMapper.updateByPrimaryKeySelective(dbTrans);
    }

    /**
     * 停用交易流水
     */
    @Transactional(rollbackFor = Exception.class)
    public void disableTrans(PatientMemberTrans patientMemberTrans) {
        PatientMemberTrans dbTrans = getTransById(patientMemberTrans.getTransId());
        if (dbTrans == null) {
            throw new BusinessFailException("交易流水不存在");
        }
        if (YesOrNoEnum.NO.getValue().equals(dbTrans.getIsEnabled())) {
            return;
        }
        dbTrans.setIsEnabled(YesOrNoEnum.NO.getValue());
        dbTrans.setUpdateUserId(patientMemberTrans.getUpdateUserId());
        dbTrans.setUpdateBy(patientMemberTrans.getUpdateBy());
        dbTrans.setUpdateTime(new Date());
        patientMemberTransMapper.updateByPrimaryKeySelective(dbTrans);
    }

    /**
     * 分页查询患者会员卡
     */
    public PageInfo<ClinicPatientMember> getMemberListByCondition(Long clinicId,Integer pageNo, Integer pageSize) {
        ClinicPatientMemberExample example = new ClinicPatientMemberExample();
        ClinicPatientMemberExample.Criteria criteria = example.createCriteria();
        if (clinicId != null) {
            criteria.andClinicIdEqualTo(clinicId);
        }
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        Long totalCount = patientMemberMapper.countByExample(example);
        if (totalCount == null || totalCount == 0) {
            return PageInfo.build();
        }
        example.setOffset(PageUtils.getOffset(pageNo, pageSize));
        example.setLimit(pageSize);
        example.setOrderByClause("create_time desc");
        List<ClinicPatientMember> memberList = patientMemberMapper.selectByExample(example);
        return new PageInfo<>(totalCount, memberList);
    }

    /**
     * 添加患者会员卡
     */
    @Transactional(rollbackFor = Exception.class)
    public void addMember(ClinicPatientMember patientMember) {
        validateMember(patientMember);
        patientMember.setVersion(CommonConstant.DEFAULT_1);
        patientMember.setSortNum(CommonConstant.DEFAULT_1);
        patientMember.setIsDelete(YesOrNoEnum.NO.getValue());
        patientMember.setIsEnabled(YesOrNoEnum.YES.getValue());
        patientMember.setCreateTime(new Date());
        patientMemberMapper.insertSelective(patientMember);
    }

    /**
     * 校验患者会员卡
     */
    public void validateMember(ClinicPatientMember member) {

    }

    /**
     * 根据主键查询患者会员卡
     */
    public ClinicPatientMember getMemberById(Long memberId) {
        if (memberId == null) {
            return null;
        }
        ClinicPatientMember member = patientMemberMapper.selectByPrimaryKey(memberId);
        if (member == null || YesOrNoEnum.YES.getValue().equals(member.getIsDelete())) {
            return null;
        }
        return member;
    }

    /**
     * 修改患者会员卡
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateMember(ClinicPatientMember patientMember) {
        patientMember.setUpdateTime(new Date());
        patientMemberMapper.updateByPrimaryKeySelective(patientMember);
    }

    /**
     * 删除患者会员卡（逻辑删除）
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteMember(ClinicPatientMember patientMember) {
        ClinicPatientMember dbMember = getMemberById(patientMember.getPatientId());
        if (dbMember == null) {
            throw new BusinessFailException("会员卡不存在");
        }
        dbMember.setIsDelete(YesOrNoEnum.YES.getValue());
        dbMember.setUpdateUserId(patientMember.getUpdateUserId());
        dbMember.setUpdateBy(patientMember.getUpdateBy());
        dbMember.setUpdateTime(new Date());
        patientMemberMapper.updateByPrimaryKeySelective(dbMember);
    }

    /**
     * 启用患者会员卡
     */
    @Transactional(rollbackFor = Exception.class)
    public void enableMember(ClinicPatientMember patientMember) {
        ClinicPatientMember dbMember = getMemberById(patientMember.getPatientId());
        if (dbMember == null) {
            throw new BusinessFailException("会员卡不存在");
        }
        if (YesOrNoEnum.YES.getValue().equals(dbMember.getIsEnabled())) {
            return;
        }
        dbMember.setIsEnabled(YesOrNoEnum.YES.getValue());
        dbMember.setUpdateUserId(patientMember.getUpdateUserId());
        dbMember.setUpdateBy(patientMember.getUpdateBy());
        dbMember.setUpdateTime(new Date());
        patientMemberMapper.updateByPrimaryKeySelective(dbMember);
    }

    /**
     * 停用患者会员卡
     */
    @Transactional(rollbackFor = Exception.class)
    public void disableMember(ClinicPatientMember patientMember) {
        ClinicPatientMember dbMember = getMemberById(patientMember.getPatientId());
        if (dbMember == null) {
            throw new BusinessFailException("会员卡不存在");
        }
        if (YesOrNoEnum.NO.getValue().equals(dbMember.getIsEnabled())) {
            return;
        }
        dbMember.setIsEnabled(YesOrNoEnum.NO.getValue());
        dbMember.setUpdateUserId(patientMember.getUpdateUserId());
        dbMember.setUpdateBy(patientMember.getUpdateBy());
        dbMember.setUpdateTime(new Date());
        patientMemberMapper.updateByPrimaryKeySelective(dbMember);
    }



    /**
     * 分页查询会员充值档位
     * @param clinicId 诊所ID
     * @param gearName 档位名称（模糊搜索）
     * @param pageNo 页码
     * @param pageSize 每页数量
     * @return 分页结果
     */
    public PageInfo<PatientMemberGearVo> getGearList(Long clinicId,String gearName, Integer pageNo, Integer pageSize) {
        PageInfo<PatientMemberGear> pageInfo = getGearListByCondition(clinicId,gearName,pageNo,pageSize);
        if(pageInfo.getTotalCount() <= CommonConstant.DEFAULT_0){
            return PageInfo.build();
        }
        List<PatientMemberGear> gearList = pageInfo.getList();
        // 将实体列表转换为DTO列表
        return new PageInfo<>(pageInfo.getTotalCount(),gearList.stream().map(gear -> {
            PatientMemberGearVo patientMemberGearVo = new PatientMemberGearVo();
            BeanUtils.copyProperties(gear, patientMemberGearVo);
            return patientMemberGearVo;
        }).collect(Collectors.toList()));
    }


    /**
     * 分页查询会员充值档位
     * @param clinicId 诊所ID
     * @param gearName 档位名称（模糊搜索）
     * @param pageNo 页码
     * @param pageSize 每页数量
     * @return 分页结果
     */
    public PageInfo<PatientMemberGear> getGearListByCondition(Long clinicId,String gearName, Integer pageNo, Integer pageSize) {
        PatientMemberGearExample example = new PatientMemberGearExample();
        PatientMemberGearExample.Criteria criteria = example.createCriteria();
        if (StringUtil.isNotBlank(gearName)) {
            criteria.andGearNameLike("%" + gearName + "%");
        }
        if(!StringUtil.isBlank(clinicId)){
            criteria.andClinicIdEqualTo(clinicId);
        }
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        Long totalCount = patientMemberGearMapper.countByExample(example);
        if (totalCount == null || totalCount == 0) {
            return PageInfo.build();
        }
        example.setOffset(PageUtils.getOffset(pageNo, pageSize));
        example.setLimit(pageSize);
        example.setOrderByClause("create_time desc");
        List<PatientMemberGear> gearList = patientMemberGearMapper.selectByExample(example);
        return new PageInfo<>(totalCount, gearList);
    }

    /**
     * 添加会员充值档位
     * @param patientMemberGear 实体
     */
    @Transactional(rollbackFor = Exception.class)
    public void addGear(PatientMemberGear patientMemberGear) {
        validateGear(patientMemberGear);
        patientMemberGear.setIsDelete(YesOrNoEnum.NO.getValue());
        patientMemberGear.setIsEnabled(YesOrNoEnum.YES.getValue());
        patientMemberGear.setCreateTime(new Date());
        patientMemberGearMapper.insertSelective(patientMemberGear);
    }

    /**
     * 校验会员充值档位
     * @param memberGear 实体
     */
    public void validateGear(PatientMemberGear memberGear) {
        // 可加入唯一性、非空校验
        memberGear.setGearName(StringUtil.removeAllWhitespace(memberGear.getGearName()));
        if (StringUtil.isBlank(memberGear.getGearName())) {
            throw new BusinessFailException("档位名称不能为空");
        }
        if (memberGear.getGearName().length() > Constants.MEMBER_GEAR_LENGTH) {
            throw new BusinessFailException("档位名称"+Constants.MEMBER_GEAR_LENGTH+"个字以内！");
        }
        if (memberGear.getPresentPrice() == null || memberGear.getPresentPrice() <= CommonConstant.DEFAULT_0) {
            throw new BusinessFailException("销售价格必须大于"+CommonConstant.DEFAULT_0);
        }
        if (memberGear.getRechargeAmount() == null || memberGear.getRechargeAmount() <= CommonConstant.DEFAULT_0) {
            throw new BusinessFailException("充值金额必须大于"+CommonConstant.DEFAULT_0);
        }
        if(StringUtil.isBlank(memberGear.getSortNum())){
            throw new BusinessFailException("请输入排序号");
        }
    }

    /**
     * 根据主键查询档位信息
     * @param gearId 主键ID
     * @return 实体
     */
    public PatientMemberGear getGearById(Long gearId) {
        if (gearId == null) {
            return null;
        }
        PatientMemberGear gear = patientMemberGearMapper.selectByPrimaryKey(gearId);
        if (gear == null || YesOrNoEnum.YES.getValue().equals(gear.getIsDelete())) {
            return null;
        }
        return gear;
    }

    /**
     * 修改会员充值档位
     * @param patientMemberGear 实体
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateGear(PatientMemberGear patientMemberGear) {
        validateGear(patientMemberGear);
        PatientMemberGear dbGear = getGearById(patientMemberGear.getGearId());
        if (dbGear == null) {
            throw new BusinessFailException("充值档位不存在");
        }
        patientMemberGear.setUpdateTime(new Date());
        patientMemberGearMapper.updateByPrimaryKeySelective(patientMemberGear);
    }

    /**
     * 删除会员充值档位（逻辑删除）
     * @param patientMemberGear 实体
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteGear(PatientMemberGear patientMemberGear) {
        PatientMemberGear dbGear = getGearById(patientMemberGear.getGearId());
        if (dbGear == null) {
            throw new BusinessFailException("充值档位不存在");
        }
        dbGear.setIsDelete(YesOrNoEnum.YES.getValue());
        dbGear.setUpdateUserId(patientMemberGear.getUpdateUserId());
        dbGear.setUpdateBy(patientMemberGear.getUpdateBy());
        dbGear.setUpdateTime(new Date());
        patientMemberGearMapper.updateByPrimaryKeySelective(dbGear);
    }

    /**
     * 启用充值档位
     * @param patientMemberGear 实体
     */
    @Transactional(rollbackFor = Exception.class)
    public void enableGear(PatientMemberGear patientMemberGear) {
        PatientMemberGear dbGear = getGearById(patientMemberGear.getGearId());
        if (dbGear == null) {
            throw new BusinessFailException("充值档位不存在");
        }
        if (YesOrNoEnum.YES.getValue().equals(dbGear.getIsEnabled())) {
            return;
        }
        dbGear.setIsEnabled(YesOrNoEnum.YES.getValue());
        dbGear.setUpdateUserId(patientMemberGear.getUpdateUserId());
        dbGear.setUpdateBy(patientMemberGear.getUpdateBy());
        dbGear.setUpdateTime(new Date());
        patientMemberGearMapper.updateByPrimaryKeySelective(dbGear);
    }

    /**
     * 停用充值档位
     * @param patientMemberGear 实体
     */
    @Transactional(rollbackFor = Exception.class)
    public void disableGear(PatientMemberGear patientMemberGear) {
        PatientMemberGear dbGear = getGearById(patientMemberGear.getGearId());
        if (dbGear == null) {
            throw new BusinessFailException("充值档位不存在");
        }
        if (YesOrNoEnum.NO.getValue().equals(dbGear.getIsEnabled())) {
            return;
        }
        dbGear.setIsEnabled(YesOrNoEnum.NO.getValue());
        dbGear.setUpdateUserId(patientMemberGear.getUpdateUserId());
        dbGear.setUpdateBy(patientMemberGear.getUpdateBy());
        dbGear.setUpdateTime(new Date());
        patientMemberGearMapper.updateByPrimaryKeySelective(dbGear);
    }
}
